<?php
namespace App\Http\Controllers\Mobile;


/**
 * Created by PhpStorm.
 * User: xhkj
 * Date: 2018/1/31
 * Time: 下午7:39
 */

use App\Jobs\SendShuJuTiJiao;

use App\Models\Shop;
use App\Models\XunDianJiLu;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class XunDianGuanLiController extends Controller{

    /**
     * 保存巡店数据
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function xun_dian_data_save(Request $request)
    {
        $user = Auth::getUser();

        file_put_contents('./巡店数据提交.txt',
            '------'.PHP_EOL.date('Y-m-d H:i:s').PHP_EOL.'提交数据:'.$request->getContent().
            PHP_EOL.'------'.PHP_EOL.PHP_EOL,FILE_APPEND);

        // 存入记录表
        $xunDianJiLu = new XunDianJiLu();
        // 查询UUID是否存在
        $data = json_decode($request->getContent(), true);
        if(count($xunDianJiLu->where("uuid",$data['uuid'])->first())){
            return $this->success(['上传成功,重复提交']);
        }

        // 提交到队列
        SendShuJuTiJiao::dispatch($request->getContent(), $user);

        return $this->success(['上传成功']);

    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function user_get_shop(Request $request){

        $params = $this->validate($request, [
            'name' => 'nullable',
            'code' => 'nullable',
        ]);

        // 分页数
        $paginate = $request->get('paginate', 10);

        $user = Auth::getUser();

        $query = Shop::query();

        foreach ($params as $key => $value) {
            if ($value) {
                $query->orWhere($key, 'like', "%".$value."%");
            }
        }

        $query->whereHas('users',function($query) use($user){
            $query->where('id',$user->id);
        });

        return $this->success($query->paginate($paginate));
    }

}